#[macro_use] extern crate structopt;
extern crate usrtrust;

use usrtrust::{ULogs,Environment};
use std::path::{Path,PathBuf};

use std::{thread, time};
use std::sync::mpsc;
use std::io::Write;
fn main() -> std::io::Result<()> {
    let e = Environment::from_dir(Path::new("/tmp/usrtos"))?;
    let logt = ULogs::from_env(&e);
    let (tx,rx) = mpsc::channel();

    let logout = thread::spawn(move || {
        let e = Environment::from_dir(Path::new("/tmp/usrtos")).unwrap();
        let logs = ULogs::from_env(&e);
        logs.reset();
        loop {
            let sig = rx.recv_timeout(time::Duration::from_millis(500)); 
            match sig {
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    logs.dump();
                },
                _default => {break;},
            }
        }
    });
    let e = Environment::from_dir(Path::new("/tmp/usrtos"))?;

    let logt = ULogs::from_env(&e);
    writeln!(*logt.sys(),"{}","This is sys log");
    writeln!(*logt.info(),"{}","This is info log");
    writeln!(*logt.dbg(),"{}","This is debug log");
    writeln!(*logt.warn(),"{}","This is warn log");
    writeln!(*logt.error(),"{}","This is error log");
    writeln!(*logt.fatal(),"{}","This is fatal log");
    logt.flush();
    for i in 0..4 {
        writeln!(*logt.dbg(),"this is {}",i);
    }
    for i in 0..4 {
        writeln!(*logt.info(),"this is {}",i);
    }
    logt.dbg().flush()?;
    logt.info().flush()?;
    thread::sleep(time::Duration::from_millis(1000));
    tx.send(0).unwrap();
    logout.join();
    Ok(())
}
